<template>
	<view class="main">
		<view>
			<view class="binding">
				你好！
			</view>
			<view class="sys">
				欢迎登录艾斯芸erp管理系统
			</view>
			<view>请同意获取手机号码以实现登录功能！</view>
			<!-- <u-button :hair-line='false' :custom-style="customStyle1" @click="toUserLogin">密码登录</u-button> -->
			<view class="popBtnView">
				<button type="primary" size='mini' form-type='submit' shape="circle" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber">同意</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					wxCode: '',
					appIndex: 'a7y7d8VpB8p',
					ticket: '5NPmkN4gxVr',
					encryptedData: '',
					iv: '',
					phone:''
				}
			};
		},
		onLoad(options) {
			if (options.ticket) {
				this.formData.ticket = options.ticket
			}
			if(uni.getStorageSync('user_phone')){
				this.formData.phone = uni.getStorageSync('user_phone')
				delete this.formData.encryptedData
				delete this.formData.iv
				this.login()
			}
			this.wxLogin()
		},
		methods: {
			// 刷新微信code
			wxLogin() {
				uni.login({
					provider: 'weixin',
					success: res => {
						this.formData.wxCode = res.code
					},
					fail: (e) => {
						uni.showModal({
							title: '提示',
							content: '微信登录失败',
						})
					}
				});
			},
			// 获取用户手机号码
			getPhoneNumber(e) {
				console.log(e)
				if (e.detail.errMsg == "getPhoneNumber:fail:user deny" || e.detail.errMsg ==
					"getPhoneNumber:fail user deny") {
					uni.showToast({
						title: '授权失败',
						icon: 'error'
					});
				} else {
					this.formData.encryptedData = e.detail.encryptedData
					this.formData.iv = e.detail.iv
					delete this.formData.phone
					uni.showLoading({
						mask: true,
						title: '请求中...'
					})
					this.login()
				}
			},
			login(){
				uni.request({
					// url: "https://e.asy315.vip/wx/user/login/wx/ma",
					url: "https://q71107k696.imdo.co/wx/user/login/wx/ma",
					method: "POST",
					data: this.formData,
					header: {
						'content-type': "application/x-www-form-urlencoded",
					},
					success: (res) => {
						if(res.data.data.status == 200){
							uni.setStorageSync('user_phone', res.data.data.user.phone)
							uni.redirectTo({
								url:"/pages/a"
							})
						}else{
							uni.showModal({
								title:'提示',
								content:res.data.msg,
								showCancel:false
							})
							this.wxLogin()
						}
						uni.hideLoading()
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.main {
		width: 100%;
		height: 80vh;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.binding {
		font-size: 32rpx;
	}

	.sys {
		font-size: 46rpx;
		font-weight: bold;
		margin: 22rpx 0 33rpx;
	}

	.popBtnView {
		text-align: center;
		margin-top: 30rpx;
	}
</style>